import { useEffect, useState, useImperativeHandle, forwardRef, useMemo } from 'react'
import { Button, Pagination, Empty, Popconfirm, message, Form, Modal, Input, Checkbox } from 'antd'
import { getImageList, delImage, editImageName } from '@/api/image'

import { QuestionCircleOutlined } from '@ant-design/icons'
import styles from './main.module.css'
function ImageMain(props: any, ref: React.Ref<any>) {
  console.log(props.checkBox)

  useImperativeHandle(ref, () => {
    return { getImgLst }
  })
  const [imgPage, setImgPage] = useState(1)
  const [imgList, setImgList] = useState([])
  const [imgListTotal, setImgListTotal] = useState(0)

  useEffect(() => {
    getImgLst()
  }, [props.selectClass, imgPage])

  const getImgLst = () => {
    getImageList(props.selectClass, imgPage).then(res => {
      if (res.status === 200) {
        let imgData = res.data.list.map((item: any) => {
          item.checked = false
          return item
        })
        setImgList(imgData)
        setImgListTotal(res.data.totalCount)
      }
    })
  }
  const delImgConfirm = (id: number) => {
    delImage({ ids: [id] }).then(res => {
      if (res.data) {
        message.success('删除成功')
        getImgLst()
      }
    })
  }
  // 重命名弹框
  const [modalOpen, setModalOpen] = useState(false)
  const [form] = Form.useForm()
  const [editId, setEditId] = useState(0)
  const eidtName = (item: any) => {
    setEditId(item.id)
    form.setFieldsValue({
      name: item.name
    })
    setModalOpen(true)
  }
  const modalSave = () => {
    form.validateFields().then(values => {
      console.log(values)
      editImageName(editId, values).then(res => {
        if (res.data) {
          message.success('修改成功')
          getImgLst()
        }
      })
    })
    setModalOpen(false)
  }
  const modalCancel = () => {
    setModalOpen(false)
  }
  const onChange = (e: number) => {
    setImgPage(e)
  }
  // 选择框
  const checkedList = useMemo(() => {
    let data: any = imgList.filter((o: any) => o.checked)
    return data
  }, [imgList])
  const onCheckboxChange = (item: any) => {
    if (checkedList.length < 1) {
      let imgData = imgList.map((el: any) => (el.id === item.id ? { ...el, checked: !el.checked } : el)) as []
      setImgList(imgData)
      props.chooseUrl(item)
    } else {
      if (checkedList[0].id === item.id) {
        let imgData = imgList.map((el: any) => (el.id === item.id ? { ...el, checked: !el.checked } : el)) as []
        setImgList(imgData)
        props.chooseUrl('')
      } else {
        message.error('只能选择一张')
      }
    }
  }
  return (
    <>
      <div className={styles.flex}>
        {imgList.length > 0 ? (
          imgList.map((item: any) => {
            return (
              <div key={item.id} style={{ width: '23%', marginBottom: '25px' }} className={styles.imgItem}>
                <div className={styles.img}>
                  <img src={item.url} alt='' style={{ width: '100%', objectFit: 'cover', height: '150px' }} />
                  <p className={styles.p}>{item.name}</p>
                </div>
                <div className={styles.btn}>
                  {props.checkBox && (
                    <Checkbox
                      checked={item.checked}
                      onChange={() => {
                        onCheckboxChange(item)
                      }}
                      className='mr-10'
                    />
                  )}
                  {!props.checkBox && (
                    <>
                      <Button
                        style={{ marginRight: '10px' }}
                        onClick={() => {
                          eidtName(item)
                        }}
                      >
                        重命名
                      </Button>
                      <Popconfirm
                        onConfirm={() => {
                          delImgConfirm(item.id)
                        }}
                        title=''
                        description='是否删除该图片？'
                        icon={<QuestionCircleOutlined style={{ color: 'red' }} />}
                      >
                        <Button>删除</Button>
                      </Popconfirm>
                    </>
                  )}
                </div>
              </div>
            )
          })
        ) : (
          <Empty description='暂无数据' />
        )}
      </div>
      <Pagination align='center' defaultCurrent={imgPage} total={imgListTotal} onChange={onChange} hideOnSinglePage={true} />
      <Modal title='重命名' centered open={modalOpen} onOk={modalSave} onCancel={modalCancel}>
        <Form form={form} name='control-hooks' style={{ maxWidth: 600 }}>
          <Form.Item name='name' rules={[{ required: true, message: '请输入图片名称' }]}>
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
}
export default forwardRef(ImageMain)
